<template>
	<view class="container-page">
		<!-- #ifdef APP -->
		<u-navbar title="认证中心" :autoBack="true" :placeholder="true">></u-navbar>
		<!-- #endif -->
		<view class="container">
			<view class="header">
				<view class="title">真人认证</view>
				<view class="subtitle">若行本人认证才能更有吸引力</view>
			</view>
			<view class="notice">
				<view class="notice-title">注意事项:</view>
				<view class="notice-items">
					<view class="notice-item">1.请保证头像与真人为同一人</view>
					<view class="notice-item">2.认证照片只会用于检测智能对比</view>
					<view class="notice-item">3.拍照仅用于认证，官方将对照片保密</view>
					<view class="notice-item">4.完成真人认证后，头像必须为本人照片</view>
					<view class="notice-item" v-if="userInfo">5.您当前设置性别的为：{{userInfo.gender==1?'男':'女'}}</view>
				</view>
			</view>
			<view class="upload-section">
				<view class="upload-title">选择认证头像</view>
				<uploadImage ref="uploadImage" @uploadSuccess='uploadSuccess' name="image" :maxCount='1' width="240rpx" height="240rpx">
				</uploadImage>
				<view class="upload-tip">{{gender}}</view>
			</view>
			<view class="submit-section">
				<button class="submit-btn" v-if="butType=='wait'" disabled="" style="opacity: 0.7;">等待上传</button>
				<button class="submit-btn" v-else-if="butType=='again'" @click="resetPic">清除选择</button>
				<button class="submit-btn" v-else-if="butType=='ok'" @click="submitAuthentication">立即认证</button>
				<view class="warning-text">
					<u-icon name="info-circle" color="#FF3E3E" size="14" style="margin-right: 12rpx;"></u-icon>
					<text>请勿出具虚假转借他人号，如账号用于违法行为，您将承担法律责任</text>
				</view>
			</view>
		</view>
		<view style="height: 20rpx;"></view>
		<u-popup :show="show" round="24rpx" mode="center" :safeAreaInsetBottom="false">
			<view class="contentBox" v-if="userInfo">
				<image class="popup-close" src="../../static/common/icon_close.png" @click="show=false" />
				<image src="../../static/common/icon_auth.png" class="popup-image"></image>
				<view class="popup-title">开启人脸认证</view>
				<view class="popup-tips"> 请整理好仪容仪表保证光线充足 </view>
				<view class="button-group">
					<view class="button1" @click="$u.throttle(handleSubmit,2000)"> 我准备好了 </view>
				</view>
			</view>
		</u-popup>
	</view>
</template>
<script>
	import uploadImage from '@/components/UploadImage.vue';
	import {
		uploadBase64Image,
		uploadFilePromise
	} from '@/utils/utils.js';
	// 修改导入方式
	import FaceAPI from '@/utils/sdk/script.js';
	export default {
		data() {
			return {
				show: false,
				auth_avatar: '',
				userInfo: null,
				gender: '', // 添加性别字段
				butType: 'wait',
				real_avater: ''
			}
		},
		components: {
			uploadImage: uploadImage
		},
		onBackPress() {
			if (this.show) {
				this.show = false
				return true
			}
		},
		onHide() {
			this.show = false
		},
		onLoad(options) {
			this.getUserInfo();
			// 监听人脸认证结果
			uni.$on('faceAuthResult', this.handleFaceAuthResult);
		},
		onUnload() {
			// 移除事件监听
			uni.$off('faceAuthResult', this.handleFaceAuthResult);
		},
		methods: {
			//重置头像（重新选择头像）
			resetPic() {
				this.$refs.uploadImage.resetPic()
				this.butType = "wait";
			},
			getUserInfo() {
				this.$Api['user'].getUserInfo().then(res => {
					this.userInfo = res.data
				})
			},
			submitAuthentication() {
				if (this.auth_avatar == '') {
					return this.$Toast('请上传认证头像')
				}
				if (this.gender != '') {
					return this.$Toast(this.gender)
				}
				this.show = true
			},
			handleSubmit() {
				if (this.auth_avatar == '') {
					return this.$Toast('请上传认证头像')
				}
				// #ifdef APP
				uni.chooseImage({
					count: 1, // 拍1张
					sourceType: ['camera'], // 只调用摄像头
					success: (res)=> {
						this.show = false
						this.handlerSuccess(res.tempFilePaths[0], this.auth_avatar)
					},
					fail: function(err) {
						console.error('调用摄像头失败', err);
					}
				});
				// #endif
				// #endef
				// 跳转到自定义相机页面
				// #ifdef H5
				uni.navigateTo({
					url: '/pages/authentication/camera?url=' + this.auth_avatar,
				});
				// #endif
			},
			uploadSuccess(e) {
				this.auth_avatar = e.fileList
				if (!e.fullurl) return false
				// 调用人脸属性识别API
				FaceAPI.callRecognizeFace(e.fullurl, (result) => {
					if (result.data.Code == "InvalidImage.NotFoundFace") {
						this.butType = "again";
						this.gender = '图像中没找到人脸，请检查您的图像中是否包含人脸或人脸太小';
					} else {
						// 获取性别信息
						const gender2 = result.data.Data.GenderList[0] === 0 ? 2 : 1;
						// console.log(result.data.Data.GenderList)
						// 这里需要根据你的业务逻辑添加账号性别的判断
						if (gender2 !== this.userInfo.gender) {
							// 显示性别不匹配提示
							this.butType = "again";
							this.gender = '上传的照片和认证的性别不匹配请重新上传'
						} else {
							this.butType = "ok";
							this.gender = '';
						}
					}
				});
			},
			// 处理人脸认证结果
			handleFaceAuthResult(data) {
				const {
					imageUrl,
					faceData
				} = data;
				const gender2 = faceData.Data.GenderList[0] === 0 ? 2 : 1;
				if (gender2 !== this.userInfo.gender) {
					this.auth_avatar = '';
					this.butType = "again";
					this.gender = '上传的照片和认证的性别不匹配请重新上传';
				} else {
					this.auth_avatar = imageUrl;
					this.butType = "ok";
					this.gender = '';
				}
			},
			async handlerSuccess(img, auth_avatar) {
				uni.showLoading({
					title: '正在上传'
				});
				try {
					const uploadResult = await uploadFilePromise(img);
					if (uploadResult.fullurl) {
						var img2 = uploadResult.fullurl;
					}
					if (uploadResult.url) {
						this.real_avater = uploadResult.url;
					}
					uni.showLoading({
						title: '正在识别'
					});
					let that = this
					FaceAPI.compareFace(img2, that.$OssUrl(auth_avatar), (result) => {
						if (result.data.Code == "InvalidImage.NotFoundFace") {
							that.$Toast(result.data.Message);
						} else {
							uni.redirectTo({
								url: '/pages/authentication/avatar-similarity?Confidence=' + result.data.Data.Confidence.toFixed(2) + "&real_avater=" + that.real_avater + "&auth_avatar=" + auth_avatar,
								success: () => {
									console.log('跳转成功');
								},
								fail: (err) => {
									console.error('跳转失败:', err);
									that.$Toast('跳转失败，请重试');
								}
							});
						}
						uni.hideLoading();
					});
				} catch (error) {
					uni.hideLoading();
					console.error('上传失败：', error);
					this.$Toast('上传失败，请重试');
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	.container-page {
		width: 100%;
		min-height: 100vh;
		background-color: #f7f8fa;
		position: relative;

		.container {
			min-height: 80vh;
			margin: 20rpx 34rpx;
			padding: 38rpx 40rpx 38rpx;
			box-shadow: 0rpx 4rpx 32rpx 0rpx #FFF0FD;
			border-radius: 32rpx;
			background: linear-gradient(180deg, #FFDAF5 0%, #FFFFFF 5%);

			.header {
				margin-bottom: 38rpx;

				.title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333333;
					margin-bottom: 16rpx;
				}

				.subtitle {
					font-size: 26rpx;
					color: #AFAFAF;
				}
			}

			.notice {
				padding: 30rpx;
				margin-bottom: 40rpx;
				background: #FFF2FD;
				border-radius: 32rpx;

				.notice-title {
					font-size: 30rpx;
					color: #F169F6;
					margin-bottom: 20rpx;
				}

				.notice-items {
					font-size: 26rpx;
					color: #9A9A9A;

					.notice-item {
						line-height: 44rpx;
					}
				}
			}

			.upload-section {
				background-color: #FFFFFF;
				border-radius: 16rpx;
				padding: 0rpx 0;
				margin-bottom: 40rpx;

				.upload-title {
					font-size: 32rpx;
					font-weight: bold;
				}

				.camera-section {
					position: relative;
					width: 240rpx;
					margin: 0 auto;

					.preview-image {
						width: 240rpx;
						height: 240rpx;
						border-radius: 16rpx;
					}
				}

				.upload-title {
					font-size: 16px;
					color: #333333;
					margin-bottom: 30rpx;
				}

				.upload-tip {
					font-size: 14px;
					color: #FF6B6B;
					margin-top: 20rpx;
					text-align: center;
				}
			}

			.submit-section {
				margin: 102rpx auto 0;

				.submit-btn {
					width: 628rpx;
					height: 88rpx;
					font-weight: bold;
					font-size: 30rpx;
					color: #FFFFFF;
					text-align: center;
					line-height: 88rpx;
					background: linear-gradient(135deg, #FE93BF 0%, #A27AFF 100%);
					box-shadow: 0rpx 4rpx 10rpx 0rpx #FDC4FF;
					border-radius: 44rpx;
				}
			}

			.warning-text {
				display: flex;
				align-items: flex-start;
				font-size: 12px;
				color: #FF6B6B;
				line-height: 32rpx;
				margin-top: 20rpx;

				.warning-text text {
					margin-left: 8rpx;
				}
			}
		}
	}

	.contentBox {
		width: 90vw;
		min-height: 440rpx;
		box-sizing: border-box;
		padding: 38rpx 44rpx 82rpx;
		box-shadow: 0rpx 4rpx 32rpx 0rpx #FFF0FD;
		border-radius: 32rpx;
		background: linear-gradient(180deg, #FFDAF5 0%, #FFFFFF 20%);
		position: relative;
		text-align: center;

		.popup-close {
			position: absolute;
			right: 0;
			top: -120rpx;
			width: 88rpx;
			height: 88rpx;
		}

		.popup-image {
			margin-top: 60rpx;
			width: 412rpx;
			height: 316rpx;
		}

		.popup-title {
			font-weight: 600;
			font-size: 34rpx;
			color: #323334;
			text-align: center;
		}

		.popup-tips {
			margin-top: 18rpx;
			font-size: 28rpx;
			color: #9A9A9A;
		}

		.button-group {
			margin-top: 68rpx;

			.title {
				display: block;
				color: #ffffff;
				text-decoration: none;
			}

			.button1 {
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 0 auto;
				width: 600rpx;
				height: 88rpx;
				font-weight: bold;
				font-size: 30rpx;
				color: #FFFFFF;
				text-align: center;
				line-height: 88rpx;
				background: linear-gradient(135deg, #FE93BF 0%, #A27AFF 100%);
				border-radius: 44rpx;
			}
		}
	}
</style>